<template>
  <div>
    <Portal to="right-disable"
            :disabled="!queryModelDefaultSetting.showSetting">
      <el-card :style="{height: (gadgetHeight + heightoffset -20) + 'px'}"
               shadow="never"
               class="aui-card--fill">
        <div>
          <div class="cardHeader"
               @mouseenter="mouseenter(true)"
               @mouseleave="mouseenter(false)"
               v-if="(gadgetSetting.headerTitle && gadgetSetting.headerTitle.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
            <span>
              <span class="cardTitle threepoints"
                    :title="gadgetSetting.headerTitle"
                    v-if='gadgetSetting.headerTitle && gadgetSetting.headerTitle.trim().length>0'>{{ gadgetSetting.headerTitle }}</span>
              <el-tooltip :open-delay="1000"
                          class="item"
                          effect="dark"
                          :content="gadgetSetting.headerDescription"
                          placement="right"
                          v-if='gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0'>
                <i class="cuifont icon_help_circle cardIcon"></i>
              </el-tooltip>
            </span>
            <MoreMenu :slicer='slicer'
                      :gadgetId='id'
                      :gadgetType='gadgetInfo.com'
                      @updateQuery="query" />
          </div>
          <div class="control-section"
               style="padding: 5px 10px;">
            <div class="content-wrapper"
                 v-loading="loading">
              <ejs-pivotview v-show="isHasData"
                             :dataSourceSettings="pivotTableDefaultSetting.dataSourceSettings"
                             :gridSettings="pivotTableDefaultSetting.gridSettings"
                             :width="pivotTableDefaultSetting.width"
                             :style="{height: gadgetHeight + 'px'}"
                             :height="gadgetHeight"
                             :allowDrillThrough="pivotTableDefaultSetting.allowDrillThrough"
                             :showTooltip="pivotTableDefaultSetting.showTooltip"
                             :showFieldList="pivotTableDefaultSetting.showFieldList"
                             :load="load"
                             :allowExcelExport="pivotTableDefaultSetting.allowExcelExport"
                             :allowConditionalFormatting="pivotTableDefaultSetting.allowConditionalFormatting"
                             :allowNumberFormatting="pivotTableDefaultSetting.allowNumberFormatting"
                             :allowPdfExport="pivotTableDefaultSetting.allowPdfExport"
                             :showToolbar="pivotTableDefaultSetting.showToolbar"
                             :allowCalculatedField="pivotTableDefaultSetting.allowCalculatedField"
                             :toolbar="pivotTableDefaultSetting.toolbar"
                             :saveReport="saveReport"
                             :fetchReport="fetchReport"
                             :toolbarRender="beforeToolbarRender"
                             :showGroupingBar='true'
                             :displayOption="pivotTableDefaultSetting.displayOption"
                             :chartSettings="pivotTableDefaultSetting.chartSettings"
                             :enableValueSorting="pivotTableDefaultSetting.enableValueSorting"
                             ref="pivotview">
              </ejs-pivotview>
              <div v-if="!isHasData"
                   class="gadget-no-data">
                <el-image @click="query()"
                          :src='noDataImageUrl'
                          fit='fill'></el-image>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
  </div>
</template>

<script>

import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import mixinViewModule from '@/mixins/report-view-module'

import moment from 'moment'
export default {
  mixins: [mixinGadgetViewModule, mixinViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  watch: {
    editMode (val) {
      if (!val) {
        this.pivotTableDefaultSetting.toolbar = ['Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'Formatting', 'FieldList']
        this.saveGadgetSetting()
      } else {
        this.pivotTableDefaultSetting.toolbar = ['Save', 'Load', 'Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'Formatting', 'FieldList']
      }
    },
    immediate: true
  },
  data () {
    return {
      gadgetSetting: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      heightoffset: 60,
      cardheight: 0,
      headText: '',
      pivotTableDefaultSetting: {
        dataSourceSettings: {
          dataSource: this.dataList,
          values: [],
          formatSettings: [],
          columns: [],
          rows: [],
          filters: [],
          calculatedFieldSettings: []
        }
      },
      dataForm: {
        searchDate: null
      },
      dataList: [],
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetSettingExclude: ['DATA'],
          gadgetType: 'bottriggerpvtablegadget',
          gadgetSetting: {
            headerTitle: '',
            headerDescription: ''
          }
        }
      }
    }
  },

  created () {
    this.query()
    if (this.editMode) {
      this.pivotTableDefaultSetting.toolbar = ['Save', 'Load', 'Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'Formatting', 'FieldList']
    }
    this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
    this.subscribeMessage('runReport', this.query)
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  mounted () {

  },
  methods: {
    load (item) {
      this.grid = this.$refs.pivotview // item
      this.gadgetHeight = (this.gadgetInfo.h * 20) - this.heightoffset
      this.cardheight = (this.gadgetHeight + this.heightoffset - 20) + 'px'
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - this.heightoffset
      this.cardheight = (this.gadgetHeight + this.heightoffset - 20) + 'px'
      this.gadgetWidth = newWPx
    },
    query () {
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      this.isHasData = false
      this.loading = true
      var _self = this
      var param = {
        // ...this.slicer,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        pageId: this.pageId,
        gadgetId: this.id
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        let pivotObj = _self.$refs.pivotview.ej2Instances
        // process config &  refresh UI
        if (res.config && res.config.report) {
          res.config.report.dataSourceSettings.dataSource = _self.dataList
          pivotObj.dataSourceSettings = res.config.report.dataSourceSettings
          // pivotObj.pivotRefresh()
          _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
        } else {
          pivotObj.dataSourceSettings.dataSource = _self.dataList
        }
        _self.isHasData = true
        pivotObj.pivotRefresh()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
      var params = {
        ..._self.slicer,
        createDateFrom: _self.slicer.dateFrom,
        createDateTo: _self.slicer.dateTo,
        dateFrom: moment(_self.slicer.dateFrom).utc().tz(this.$store.state.user.timezoneId).format('YYYY-MM-DD'),
        dateTo: moment(_self.slicer.dateTo).utc().tz(this.$store.state.user.timezoneId).format('YYYY-MM-DD'),
        businessId: this.pageId,
        gadgetId: this.id,
        timezoneOffset: this.$store.state.user.timezoneOffset
      }
      this.$interface.clientDesired.getTriggerReportDataApi(params).then(({ data: res }) => {
        _self.verifyHasData(res)
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        _self.dataList = res.data
        _self.isHasData = true
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.isHasData = true
      })
    },
    saveGadgetSetting () {
      var _self = this
      var pvtable = JSON.parse(_self.reportSetting)
      pvtable.dataSourceSettings.dataSource = null
      pvtable.pivotValues = null
      const params = {
        gadgetSetting: {
          report: pvtable
        },
        gadgetId: this.id
      }
      // putReportsSettingApi
      this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
      })
    }
  }
}
</script>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.e-custom-class {
  text-decoration: underline;
}
.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}
</style>
